package com.dongfg.zcmserver.utils;

import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * security key generator using Base64(MD5(username)),then sub string.
 * Created by 13071472 on 2015/11/3.
 */
public class DigestUtils {

    // substring start index.
    private static final int SUB_IDX = 13;

    // security key length
    private static final int KEY_LENGTH = 8;

    /**
     * generateSecurityKey security key by username.
     *
     * @param username
     * @return subtring of base64(md5(username))
     */
    public static String generateSecurityKey(String username) {
        String key = new String(Base64.getEncoder().encode(org.apache.commons.codec.digest.DigestUtils.md5(username)));
        return key.substring(SUB_IDX, SUB_IDX + KEY_LENGTH);
    }

    public static String generateDigestAuth(String username,String securityKey){
        try {
            return DigestAuthenticationProvider.generateDigest(username+":"+securityKey);
        } catch (NoSuchAlgorithmException e) {
            // ignore,Unlikely to occur
        }
        return "";
    }
}
